package com.cypher.encryptionanddecryption.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONObject;
import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.activity.MainActivity;
import com.cypher.encryptionanddecryption.adapter.CommunicationAdapter;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothManagerSingleton;
import com.cypher.encryptionanddecryption.bluetooth.ExpandBroadcastReceiver;
import com.cypher.encryptionanddecryption.dao.CommunicationDao;
import com.cypher.encryptionanddecryption.dao.impl.CommunicationDaoImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通信列表界面
 * @author: 古霸天
 * @date: 2020/11/16
 */
public class CommunicationFragment extends Fragment {

    private EditText searchTxt;
    public EditText getSearchTxt() {
        return searchTxt;
    }
    private Button searchBtn;
    private ListView listView;
    private MainActivity mainActivity;
    private BluetoothGattManager gattManager;
    private CommunicationAdapter communicationAdapter;
    private CommunicationDao communicationDao;
    private List<CommunicationBean> communicationBeans = new ArrayList<CommunicationBean>();
    private boolean loading = false;
    private CommunicationFloatingFragment communicationFloatingFragment;
    private boolean setAdapter = false;
    private Handler handler;
    /**
     * 定义协议ID，默认为空
     */
    private Integer protocolId = null;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_communication_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 获取主线程activity
        mainActivity = (MainActivity) BluetoothManagerSingleton.getInstance().getActivity();
        // 初始化子线程
        handler = new Handler();
        // 初始化数据查询服务
        communicationDao = new CommunicationDaoImpl();
        // 初始化列表
        listView = view.findViewById(R.id.communication_list);

        init(view);
        // 初始化浮动按钮
        communicationFloatingFragment = mainActivity.getCommunicationFloatingFragment();

        communicationAdapter = new CommunicationAdapter(view.getContext());

        gattManager = getGattManager();

        listView.setOnItemClickListener((AdapterView<?> parent, View v, int position, long id) -> {
            cutActivity(parent, position);
        });
        isSetProtocol();
    }

    private void init (View view) {
        // 初始化查询组
        searchTxt = view.findViewById(R.id.search);
        Drawable searchDrawable = ContextCompat.getDrawable(view.getContext(), R.drawable.search3);
        searchDrawable.setBounds(0, 0, 50, 50);
        searchTxt.setCompoundDrawables(searchDrawable, null, null, null);
        // 初始化查询组
        searchBtn = view.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener((v) -> {
            if (checkProtocolIdIsNull()) {
                return;
            }
            // 渲染列表数据
            readerListView(searchTxt.getText().toString().trim());
        });
    }

    /**
     * 校验是否设置协议类型，未设置协议类型转到设置界面设置协议
     */
    private void isSetProtocol() {
        /**
         * 如果为空进入设置界面
         */
        if (mainActivity.getProtocolId() == null) {
            // 设置按钮选中
            mainActivity.getSettingsBtn().setChecked(true);
            final AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(mainActivity, R.style.AlertDialog);
            normalDialog.setMessage("是否进入设置界面设置协议类型?");
            normalDialog.setPositiveButton("确定", (DialogInterface dialog, int which) -> {
                // 进入设置界面
                List<Fragment> fragments = new ArrayList<>();
                fragments.add(mainActivity.getSettingsFragment());
                mainActivity.showFragment(fragments);
            });
            normalDialog.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                // 选中通信列表按钮
                mainActivity.getCommunicationBtn().setChecked(true);
            });
            normalDialog.show();
        }
    }

    /**
     * 页面切换隐藏时触发该事件
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // 当页面为显示时触发该事件
        if (false == hidden) {
            // 加载数据
            loadDataByProtocolId();
        }
    }

    /**
     * 根据协议ID加载数据
     */
    private void loadDataByProtocolId() {

        if (checkProtocolIdIsNull()) {
            return;
        }

        // 如果历史协议ID为空或当前协议ID和历史协议ID不同，刷新页面
        if (this.protocolId == null || (mainActivity.getProtocolId().intValue() != this.protocolId.intValue())) {

            // 渲染列表数据
            readerListView(searchTxt.getText().toString().trim());
        }
    }

    private boolean checkProtocolIdIsNull() {
        Integer protocolId = mainActivity.getProtocolId();
        // 未设置协议类型
        if (protocolId == null) {
            Toast.makeText(mainActivity, "请在设置界面设置协议类型", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
    /**
     * 进入对话界面
     * @param parent
     * @param position
     */
    private void cutActivity (AdapterView<?> parent, int position) {
        // 打开通信页面
        gattManager = getGattManager();
        if (gattManager == null || !gattManager.isGattConnected()) {
            Toast.makeText(mainActivity, "请先连接蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        CommunicationAdapter adapter = (CommunicationAdapter) parent.getAdapter();
        CommunicationBean bean = adapter.getCommunicationBeans().get(position);
        Intent intent = new Intent(mainActivity, BluetoothCommunicationActivity.class);
        intent.putExtra("bean", JSONObject.toJSONString(bean));
        intent.putExtra("protocolId", mainActivity.getProtocolId());
        mainActivity.startActivity(intent);
    }
    private BluetoothGattManager getGattManager() {
        if (gattManager == null) {
            gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();
        }
        return gattManager;
    }

    /**
     * 渲染列表数据
     */
    protected void readerListView(String condition) {
        // 执行浮动按钮动画效果
        communicationFloatingFragment.setBtnAnimation();

        // 获取列表数据
        setCommunicationBeans(condition);

        clearList();
        // 程序0.5秒后执行，保证获取数据线程执行完成
        // 在子线程中执行渲染操作，防止程序进入假死状态
        handler.postDelayed(() -> {
            if (ExpandBroadcastReceiver.network) {
                long time = new Date().getTime();
                while (true) {
                    if (loading) {

                        communicationAdapter.setCommunicationBeans(communicationBeans);
                        communicationAdapter.notifyDataSetChanged();
                        // 第一次需要向列表设置适配器
                        if (!setAdapter) {
                            listView.setAdapter(communicationAdapter);
                            setAdapter = true;
                        }
                        // 渲染成功设置协议ID
                        protocolId = mainActivity.getProtocolId();
                        // 保证下载刷新加载的是最新数据
                        loading = false;
                        break;
                    }
                    // 超时一秒，中断循环
                    if (new Date().getTime() - time > 1000) {
                        Toast.makeText(mainActivity, "数据加载失败，请检查网络是否可用", Toast.LENGTH_SHORT).show();
                        // 保证下载刷新加载的是最新数据
                        loading = false;
                        break;
                    }
                }
            } else {
                Toast.makeText(mainActivity, "网络不可用，请检查网络连接", Toast.LENGTH_SHORT).show();
            }
            // 如果是刷新按钮触发监听事件，需要清理刷新按钮动画
            communicationFloatingFragment.clearBtnAnimation();
        }, 500);
    }
    /**
     * 根据条件查询通信信息
     * @param queryCondition
     */
    private void setCommunicationBeans(String queryCondition) {
        new Thread(() -> {
            // 等待上个线程执行完成
            // 网络可用，调用数据库数据
            if (ExpandBroadcastReceiver.network) {
                int protocolId = mainActivity.getProtocolId();
                // 如果是津燃协议，则取2.5协议的数据
                if (protocolId == 2) protocolId = 0;
                communicationBeans = communicationDao.listCommunicationBean
                        (protocolId, queryCondition);
            }
            loading = true;
        }).start();
    }
    /**
     * 清空列表
     */
    protected void clearList() {
        if (communicationAdapter.getCommunicationBeans() != null) {
            communicationAdapter.getCommunicationBeans().clear();
            communicationAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 线程睡眠
     * @param millis
     *      睡眠时间
     */
    private void sleep(int millis) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
